var express = require('express');
var conn = require('../public/javascripts/connect');
var judge_login = require('../public/javascripts/judge_login');
var router = express.Router();

var user={};
router.get("/",async function (req, res){
    user.zxt=req.query;
    let Jurisdiction=null;
    if(req.cookies.jinshan_rabbing){
        Jurisdiction=await judge_login.judgelogin(req.cookies.jinshan_rabbing);
        console.log("Jurisdiction",Jurisdiction);
        if(Jurisdiction){
            user.department_number=Jurisdiction.department_number;
            user.real_name=Jurisdiction.real_name;
        }
    };
    console.log("usersfsdbfs",user)
    if(Jurisdiction){
        res.render("newAnalysis",{user})
    }else{
        res.render('login',{login:"您还没有登录:请登录"})
    }
})


router.post('/AnalysisCon', async function (req, res, next) {//分析条件
    var object = req.body;
    console.log("dsaf:", object);
    var bumens = [];
    // 部门数组
    if (object.name.indexOf("、") != -1) {
        bumens = object.name.split('、');
    } else{
        bumens.push(object.name);
    }
    console.log("bumens:", bumens);

    // 月份数组
    var months = [];
    object.month.substr(1).replace(/\d+/g, function () {
        for (var a = 1; a <= arguments[0]; a++) {
            months.push(a);
        }
    });
    var datas = [];
    for (var i in bumens) {
        var data = [];
        var year = object.year == "2017" ? "去年同期实际值" : "当月实际值";
        for (var j in months) {
            // 从数据库获取数据
            var value;
            var sql1 = "SELECT " + year + " FROM " + bumens[i] + "_2018_" + months[j] + " WHERE 科目 = '" + object.yewuName + "'";
            await new Promise((res1)=>{
                conn.connection2.query(sql1, function (err, result) {
                    if (err) {
                        console.log('[SELECT ERROR] - ', err.message);
                        return;
                    }
                    result[0] = result[0] == undefined ? 0 : result[0][year];
                    value=result[0];
                    res1(true)
                })
            })
            data.push(value)
        }
        datas.push(data);
    }
    object.data = JSON.stringify(datas);
    console.log("usersfsdbfs", object)

    var sql2 = "INSERT INTO analysis_conditions VALUES (0,now(),'" + user.real_name + "','" + object.title + "', '" + object.model + "', '" + object.leixing + "','" + object.jibie + "', '" + object.name + "', '" + object.year + "', '" + object.month + "', '" + object.yewuName + "', '" + object.data + "')";
    conn.connection2.query(sql2, function (err, result) {
        if (err) {
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }
        console.log("result:", result);
    })
    res.json({bbb:true});
})
module.exports = router;